<?php
include_once('common.php');
include_once('sqlcommon.php');

function settle($date, $channel_idList, $sendMail){
	$error_msg="";
	foreach($channel_idList as $channel_id){
		
		if($channel_id<=0){
			continue;
		}
		$resultList = getChannelResultByDate($channel_id, $date);
		if(sizeof($resultList)==0){
			// There is no result, send mail
			$error_msg.="There is no result of ".$channel_id."\n<br/>";
			continue;
		}

		// Get all tickets
		$ticketList = getTicketByChannelDate($channel_id, $date);
		foreach($ticketList as $ticket){
			settleTicket($resultList, $ticket);
		}

		// Calculate win lost
		$win_lose=calculateWinLose($channel_id, $date);
		if(sizeof($win_lose)==0){
			$error_msg.="There is no ticket of ".getChannelName($channel_id)."\n<br/>";
			continue;
		}

		$error_msg.=" Win lose summary of " . getChannelName($channel_id). " :";
		$error_msg.=" member-win-lose: ". $win_lose[0]["member_win_lose"];
		$error_msg.=", agent_win_lose: ". $win_lose[0]["agent_win_lose"];
		$error_msg.=", affiliate_win_lose: ". $win_lose[0]["affiliate_win_lose"];
		$error_msg.=", host_win_lose: ". $win_lose[0]["host_win_lose"]."\n<br/>";
	}

	if($sendMail){
		sendMail("Settle result at " . $date->format("Y-m-d"), $error_msg);
	}
	else{
		echo $error_msg;
	}
}

$date = isset($_REQUEST['open_date'])?date_create_from_format('Y-m-d',$_REQUEST['open_date']):(new DateTime());
$sendMail=isset($_REQUEST['send_mail'])?$_REQUEST['send_mail']==='true':true;
$type=isset($_REQUEST['type'])?$_REQUEST['type']:'MN';
$dayOfWeek=$date->format("N");
$channelList =isset($_REQUEST['channel_id_list'])?explode(";", $_REQUEST['channel_id_list']):getChannelIdListByDay($dayOfWeek,$type);

settle($date, $channelList, $sendMail);

?>